package cn.lingyangwl.agile.auth.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.lingyangwl.agile.auth.assembly.ThirdAuthAssembly;
import cn.lingyangwl.agile.auth.model.rqrs.third.ThirdAuthUser;
import cn.lingyangwl.agile.auth.model.rqrs.third.WxMaLoginReq;
import cn.lingyangwl.agile.auth.service.WxAuthService;
import cn.lingyangwl.agile.dynamic.client.AbstractClientProcess;
import cn.lingyangwl.agile.dynamic.client.wx.WxMaWrapClient;
import cn.lingyangwl.agile.dynamic.client.wx.WxMpWrapClient;
import cn.lingyangwl.agile.model.enums.AuthErrorEnum;
import cn.lingyangwl.agile.model.enums.ConfigDefineEnum;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Slf4j
@Service
public class WxAuthServiceImpl implements WxAuthService {

    @Resource
    private ThirdAuthAssembly thirdAuthAssembly;

    @Override
    public ThirdAuthUser getWxLoginInfo(WxMaLoginReq req) throws WxErrorException {
       try {
           WxMpWrapClient wxMpService = ((WxMpWrapClient) AbstractClientProcess.getDynamicClient(ConfigDefineEnum.WX_MP));
           WxMaService wxMaService = ((WxMaWrapClient) AbstractClientProcess.getDynamicClient(ConfigDefineEnum.WX_MA)).getWxMaService();
           WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(req.getCode());
           log.info("微信登录- req: {}, res: {}", JSON.toJSONString(req), sessionResult);
           if (Objects.isNull(sessionResult)) {
               throw new BizException(AuthErrorEnum.TOKEN_EXPIRED);
           }

           // 解密用户信息
           WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionResult.getSessionKey(),
                   req.getEncryptedData(), req.getIv());
           if (null == wxUserInfo) {
               throw new BizException(AuthErrorEnum.WX_USER_NOT_EXIST);
           }
           ThirdAuthUser thirdAuthUser = thirdAuthAssembly.toThirdAuthUser(wxUserInfo);

           thirdAuthUser.setOpenId(sessionResult.getOpenid());
           return thirdAuthUser;
       } catch (WxRuntimeException e) {
           log.error("error: ", e);
           throw new BizException(AuthErrorEnum.WX_DATA_PARSE_FAIL);
       }
    }
}
